<template>
  <div class="upload-img">
    <el-upload
      ref="upload"
      class="avatar-uploader"
      action=""
      list-type="picture"
      :show-file-list="false"
      :http-request="diyRequest"
      :multiple="multiple"
      :auto-upload="autoUpload"
    >
      <el-image
        v-if="idCardImgUrl && !btn && showImg"
        :src="idCardImgUrl"
        name="idCardImgUrl"
        class="avatar"
        @error="imgLoadError"
        fit="cover"
      ></el-image>
      <div v-else-if="!btn" class="div-plus">
        <div class="div-plus-box">
          <i class="el-icon-plus avatar-uploader-icon"></i>
          <div class="el-upload__text">支持jpg/gif/png格式</div>
        </div>
      </div>
      <div v-else class="btn">
        <slot name="button"></slot>
      </div>
    </el-upload>
    <!-- 只有上传文件类型为视频的时候才有进度条 -->
    <!-- <el-progress
      style="margin: 5px"
      :width="70"
      :percentage="100"
    ></el-progress> -->
  </div>
</template>

<script>
import { qiniuUploadFile } from '@/utils/QiniuUpload';
export default {
  data() {
    return {
      idCardImgUrl: "", // 图片路径
      idCardIsUpload: false, // 是否需要进度条
      idCardUploadPercentage: 0, // 上传进度(仅视频有进度条)
      errorImgUrls: [],
    };
  },
  props: {
    /*可以在使用组件的时候传入一个支持上传的图片格式的数组进来，不传默认default数组*/
    supportType: {
      //支持上传文件的格式
      default: () => ["image/jpeg", "image/jpg", "image/png"],
      type: Array,
    },

    type: {
      type: String,
      default: "image",
    },
    api: {
      type: String,
      default: "",
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 批量上传
    multiple: {
      type: Boolean,
      default: false,
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
    btn: {
      type: Boolean,
      default: false,
    },
    showImg: {
      type: Boolean,
      default: true
    },
    bigImage: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
  },
  methods: {
    /*父组件执行的方法*/
    setEditImg(path) {
      console.log(path)
      this.idCardImgUrl = path ? path : "";
    },
    showProcess(idCardIsUpload, idCardUploadPercentage) {
      this.$emit('showProcess',idCardIsUpload, idCardUploadPercentage)
    },
    /*自定义上传的方法*/
    async diyRequest(param) {
      console.log('上传类型', this.type === 'audio', param)
      if (this.type == "video") {
        console.log('文件名字', param)
        // let fileSize = param.file.size / 1024 / 1024 < 50;
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb",
            "video/mov",
          ].indexOf(param.file.type) == -1
        ) {
          this.$message.error("请上传正确的视频格式");
          return false;
        }
        // if (!fileSize) {
        //   this.$message.error("视频大小不能超过50MB");
        //   return false;
        // }
        this.$emit('getVideoName', param.file.name)
      } else if (this.type == "image") {
        console.log('文件名字', param)
        /*对上传图片的大小和格式校验*/
        const isLt10M = param.file.size / 1024 / 1024 < 4;
        if (this.supportType.indexOf(param.file.type) == -1) {
          let supportType = this.supportType;
          let msg = "";
          supportType.map((res) => {
            msg += res.substring(6) + "/";
          });
          let newMsg = msg.slice(0, msg.length - 1);
          this.$message.error(`请上传正确的图片格式！支持的格式有：` + newMsg);
          return;
        }
        if (!isLt10M) {
          this.$Message.error("上传图片大小不能超过4MB哦!");
          return;
        }
      } else if (this.type === 'audio') {
        // console.log('params', params)
        // const isAudio = param.file.type === 'audio/mpeg' || file.type === 'audio/ogg';
        const isLt500KB = param.file.size / 1024 / 1024 < 4;
        console.log('音频', isLt500KB)
        // if (!isAudio) {
        //   return this.$message.error('上传的文件只能是音频格式!');
        // }
        if (!isLt500KB) {
          return this.$message.error('上传的音频文件不能超过 4MB!');
        }
        // return isAudio && isLt500KB;
      } else {
        return this.$message.error("您上传的文件类型错误");
      }
      const fileObj = param.file;

      this.$emit("change", fileObj);
      console.log('fileObj', fileObj);
      const form = new FormData();
      form.append("filename", fileObj);
      if (this.bigImage) {
        /*走后台接口，这里自行换成自己的api*/
        this.$api[this.api](form, { ...this.params }, (progressEvent) => {
          console.log('progressEvent111111', progressEvent)
          if (progressEvent.lengthComputable) {
            console.log(progressEvent)
            this.idCardIsUpload = true; // 显示进度条
            this.idCardUploadPercentage = parseInt(progressEvent.loaded / progressEvent.total * 100); // 动态获取文件上传进度
            console.log('idCardUploadPercentage', this.idCardUploadPercentage)
            if (this.idCardUploadPercentage >= 99) {
              this.idCardUploadPercentage = 99 // 一秒后关闭进度条
            }
            this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
          }
        }).then((res) => {
          // this.idCardIsUpload = false;
          // this.showProcess(this.idCardIsUpload, 100)
          if (res.status == "$SUCCESS") {
            this.idCardUploadPercentage = 100
            this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
            setTimeout(() => {
              this.idCardIsUpload = false
              this.idCardUploadPercentage = 0
              this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
            }, 1000);
            // this.idCardImgUrl = res.data.basePath + res.data.url;
            this.idCardImgUrl = URL.createObjectURL(fileObj);
            this.showProcess(this.idCardIsUpload, 0)
            /*成功之后将图片路径暴露给父组件去显示图片*/
            this.$emit("setCardPic", res?.data?.url || res.result, this.idCardImgUrl);
          } else {
            this.$message.error(res.message);
            this.$emit('getVideoName', '')
          }
          this.idCardUploadPercentage = 0
        });
      } else {
        // 统一上传到七牛云，然后把获取到的地址抛出去
        let res = await qiniuUploadFile(fileObj, 'artworks', (progressEvent) => {
          console.log('progressEvent', progressEvent)
          if (progressEvent.total.percent) {
            console.log(progressEvent)
            this.idCardIsUpload = true; // 显示进度条
            this.idCardUploadPercentage = parseInt(progressEvent.total.percent); // 动态获取文件上传进度
            console.log('idCardUploadPercentage', this.idCardUploadPercentage)
            if (this.idCardUploadPercentage >= 99) {
              this.idCardUploadPercentage = 99 // 一秒后关闭进度条
            }
            this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
          }
        });
        // if (res.status == "$SUCCESS") {
          this.idCardUploadPercentage = 100
          this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
          setTimeout(() => {
            this.idCardIsUpload = false
            this.idCardUploadPercentage = 0
            this.showProcess(this.idCardIsUpload, this.idCardUploadPercentage)
          }, 1000);
          // this.idCardImgUrl = res.data.basePath + res.data.url;
          this.idCardImgUrl = URL.createObjectURL(fileObj);
          this.showProcess(this.idCardIsUpload, 0)
          /*成功之后将图片路径暴露给父组件去显示图片*/
          this.$emit("setCardPic", res.key, this.idCardImgUrl);
        // } else {
          // this.$message.error(res.message);
          // this.$emit('getVideoName', '')
        // }
        this.idCardUploadPercentage = 0
      }
    },
    /*当图片显示失败的时候，我会重复10次赋值图片，成功显示就退出，还是失败就会显示失败*/
    imgLoadError(error) {
      let isExist = false;
      console.log('errr', error)
      if (!error.path) return;
      const src = error.path[0].src.split("?")[0];
      if (this.errorImgUrls.length == 0) {
        this.errorImgUrls.push({ src: src, number: 1 });
      }
      for (let i = 0; i < this.errorImgUrls.length; i++) {
        if (src === this.errorImgUrls[i].src) {
          isExist = true;
          while (this.errorImgUrls[i].number < 10) {
            this.errorImgUrls[i].number++;
            const timestamp1 = Date.parse(new Date());
            this[error.path[0].name] = src + "?t=" + timestamp1;
          }
        }
      }
      if (!isExist) {
        //首次上传（不在错误数组图片中，需要执行循环三次赋值）
        this.errorImgUrls.push({ src: src, number: 1 });
        this.imgLoadError(error);
      }
    },
    submit() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="less" scoped>
.div-plus {
  width: 240px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f3f4f4;

  .div-plus-box {
    text-align: center;

    .el-upload__text {
      font-size: 16px;
      font-weight: 400;
      color: #999999;
      line-height: 19px;
    }
  }
}

.btn {
  display: inline-block;
}
</style>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  text-align: center;
}
.avatar {
  width: 240px;
  height: 240px;
  display: block;
}
</style>
